<template>
	<view class="card_chart">
		<uni-card margin="0">
			<uni-segmented-control styleType="text" :current="current" :values="items"
				@clickItem="onClickItem"></uni-segmented-control>
			<view class="content">
				<!-- 日期选择 -->
				<view class="date_mouth">
					<view class="date_mouth_left" @click="onLeftArrow">
						<text class="iconfont icon-zuojiantou"></text>
					</view>
					<view class="date_mouth_center" ref="dateMouthCenter" @click="selectDate">
						<text>{{dateValue}}</text>
						<text class="iconfont icon-rili"></text>
					</view>
					<view class="date_mouth_right" @click="onRightArrow">
						<text class="iconfont icon-youjiantou1"></text>
					</view>
				</view>
				<!-- charts表格 -->
				<view class="charts-box">
					<view class="title" v-if="type === 3">
						<text class="word" v-show="current===0">当日发电量：</text>
						<text class="word" v-show="current===1">当月发电量：</text>
						<text class="word" v-show="current===2">当年发电量：</text>
						<text class="count">{{allPower}}kWh</text>
						<!-- <text class="word" v-show="current===0">当日满发小时：</text>
						<text class="word" v-show="current===1">当月满发小时：</text>
						<text class="word" v-show="current===2">当年满发小时：</text>
						<text class="count">{{fullHour}}h</text> -->
					</view>
					<view class="charts" v-if="chartData.series.length">
						<qiun-data-charts :type="chartsType" :opts="opts" :chartData="chartData" :ontouch='true' />
					</view>
					<o-empty v-else />
				</view>
			</view>
		</uni-card>

		<!-- 弹窗 -->
		<uni-popup ref="popup" background-color="#fff" @change="onPopupChange">
			<!-- 日期滑动选择 -->
			<picker-view ref="picker" v-if="visible" :indicator-style="indicatorStyle" :value="value"
				@change="bindChange" class="picker-view">
				<picker-view-column>
					<view class="item" v-for="(item,index) in years" :key="index">{{item}}年</view>
				</picker-view-column>
				<picker-view-column v-show="current!==2">
					<view class="item" v-for="(item,index) in months" :key="index">{{item}}月</view>
				</picker-view-column>
				<picker-view-column v-show="current===0">
					<view class="item" v-for="(item,index) in days" :key="index">{{item}}日</view>
				</picker-view-column>
			</picker-view>
		</uni-popup>
	</view>
</template>

<script>
	import {
		getDeviceAmountMap, //1
		getDeviceTempMap, //2
		getStationHistoryData, //3
		getQueryMeterDetails, //4
	} from "@/common/api/api.js"
	export default {
		props: {
			sn: {
				type: String
			},
			type: {
				type: Number
			},
			did: {
				type: String
			}
		},
		data() {
			const date = new Date()
			const years = []
			const year = date.getFullYear()
			const months = []
			const month = date.getMonth() + 1
			const days = []
			const categories = []
			const day = date.getDate()
			for (let i = 1990; i <= date.getFullYear(); i++) {
				years.push(i)
			}
			for (let i = 1; i <= 12; i++) {
				months.push(i)
			}
			for (let i = 1; i <= 31; i++) {
				days.push(i)
			}
			for (let i = 1; i <= 16; i++) {
				categories.push('P' + i)
			}
			return {
				items: ['日', '月', '年'],
				current: 0,
				years,
				year,
				months,
				month,
				days,
				day,
				allPower: '--',
				fullHour: "--",
				monthCount: 0, //月发电量
				yearCount: 0, //年发电量
				value: [9999, month - 1],
				visible: true,
				indicatorStyle: `height: 50px;`,
				chartData: {
					categories: this.type === 3 ? [] : categories,
					series: []
				},
				opts: {
					color: ["#1890FF", "#91CB74", "#FAC858", "#EE6666", "#73C0DE", "#3CA272", "#FC8452", "#9A60B4",
						"#ea7ccc"
					],
					touchMoveLimit: 24,
					enableScroll: true,
					// dataLabel: {
					// 	fontSize: 10,
					// 	color: '#ffffff',
					// 	fontWeight: 'bold',
					// 	// 可选：加背景提升可读性（小程序支持）
					// 	background: {
					// 		color: '#000000',
					// 		opacity: 0.6
					// 	},
					// 	show: true
					// },
					padding: [15, 15, 0, 5],
					legend: {},
					title: {
						name: 'MWh'
					},
					xAxis: {
						disableGrid: true,
						rotateLabel: true,
						rotateAngle: 60,
						marginTop: 10,
						scrollShow: true,
						itemCount: 8
					},
					yAxis: {
						gridType: "dash",
						dashLength: 2
					},
					extra: this.type === 3 ? {
						width: 0.5,
						area: {
							type: "curve",
							opacity: 0.7,
							addLine: true,
							width: 1,
							gradient: true,
							activeType: "hollow"
						}
					} : {
						line: {
							type: "curve",
							width: 2,
							activeType: "hollow"
						}
					}
				}
			};
		},
		computed: {
			dateValue() {
				if (this.current === 0) {
					return this.year + '-' + this.month + '-' + this.day
				} else if (this.current === 1) {
					return this.year + '-' + this.month
				}
				return this.year
			},
			//charts是否显示area，line，clounm
			chartsType() {
				if (this.type === 3 || this.type === 4) {
					if (this.current === 0) {
						return 'area'
					} else {
						return 'column'
					}
				} else {
					return 'line'
				}
			}
		},
		watch: {
			type(n, o) {
				this.getChartsData()
			}
		},
		methods: {
			//年月日切换
			onClickItem(e) {
				if (this.current === e.currentIndex) {
					return
				}
				if (this.current != e.currentIndex) {
					this.current = e.currentIndex;
				}
				this.getChartsData(this.type)
			},
			//左箭头
			onLeftArrow() {
				if (this.current === 1) {
					if (this.month <= 1) {
						return
					}
					this.month--
				} else if (this.current === 2) {
					if (this.year <= this.years[0]) {
						return
					}
					this.year--
				} else {
					if (this.day <= 1) {
						return
					}
					this.day--
				}
				this.getChartsData(2)
			},
			//右箭头
			onRightArrow() {
				if (this.current === 1) {
					if (this.month >= 12) {
						return
					}
					this.month++
				} else if (this.current === 2) {
					if (this.year >= this.years[this.years.length - 1]) {
						return
					}
					this.year++
				} else {
					if (this.month >= 31) {
						return
					}
					this.day++
				}
				this.getChartsData(2)
			},
			//年月选择器
			bindChange: function(e) {
				const val = e.detail.value
				this.year = this.years[val[0]]
				this.months[val[1]] && (this.month = this.months[val[1]])
				this.days[val[2]] && (this.day = this.days[val[2]])
			},
			//弹出选择器
			selectDate() {
				this.$refs.popup.open("bottom")
			},
			//选择器显示隐藏
			onPopupChange(e) {
				if (!e.show) {
					this.getChartsData(2)
				}
			},
			//获取表格数据
			async getChartsData(type = 1) {
				this.chartData.series = []
				this.chartData.categories = []
				const token = uni.getStorageSync('Token')
				let res;
				if (this.type === 1) {
					let params = {
						monitorSn: this.sn,
						timeType: this.current + 1,
						token
					}
					res = await getDeviceAmountMap(params)
					let data = Object.values(res.data)
					data.forEach((item, index) => {
						let serie = {
							name: 'B' + (index + 1),
							data: item
						}
						this.chartData.series.push(serie)
					})
				} else if (this.type === 2) {
					let params = {
						monitorSn: this.sn,
						createTime: this.year + '-' + this.month + '-' + this.day + ' 00:00:00',
						token
					}
					res = await getDeviceTempMap(params)
					let data = Object.values(res.data)
					data.forEach((item, index) => {
						let serie = {
							name: 'B' + (index + 1),
							data: item
						}
						this.chartData.series.push(serie)
					})
				} else if (this.type === 3) {
					const {
						startTime,
						endTime
					} = this.filterDate()
					let params = {
						id: this.did,
						timeType: this.current + 1,
						token
					}
					params.startTime = startTime
					params.endTime = endTime
					res = await getStationHistoryData(params)
					let datas = [];
					let data = [];
					for (let [key, value] of Object.entries(res.data)) {
						if (key === 'fullHour') {
							this.fullHour = value
							continue
						}
						if (key === 'yearPower' || key === 'monthPower' || key === 'dayPower') {
							this.allPower = value
							continue
						}
						datas.push([key, value])
					}
					datas.sort().forEach(item => {
						switch (this.current) {
							case 0:
								this.chartData.categories.push(item[0].slice(-8, -3))
								data.push(item[1].todayEnergy)
								break;
							case 1:
								this.chartData.categories.push(item[0])
								data.push(item[1])
								break;
							case 2:
								this.chartData.categories.push(item[0])
								data.push(item[1])
								break;
							default:
								break;
						}
					})
					this.chartData.series.push({
						name: "发电量(MWh)",
						pointShape: "none",
						data,
						dataLabel: true
					})
					return
				} else if (this.type === 4) {
					const {
						startTime,
						endTime
					} = this.filterDate()
					let timeType = 1
					if (this.current === 2 || this.current === 1) {
						timeType = this.current + 2
					}
					let params = {
						id: this.did,
						timeType,
						token
					}
					params.startTime = startTime
					params.endTime = endTime
					let res = await getQueryMeterDetails(params)
					let datas = [];
					let data = []
					let data1 = []
					let data2 = []
					let data3 = []
					for (let [key, value] of Object.entries(res.data)) {
						if (key === 'meter') {
							this.$emit('sendMeter', value)
							continue
						}
						datas.push([key, value])
					}
					datas.sort().forEach(item => {
						switch (this.current) {
							case 0:
								this.chartData.categories.push(item[0].slice(-8, -3))
								data1.push(item[1][0].groupElel * 1)
								data2.push(item[1][0].fpFKwh * 1)
								data3.push(item[1][0].rfpFKwh * 1)
								break;
							case 1:
								this.chartData.categories.push(item[0])
								data.push(item[1][0])
								break;
							case 2:
								this.chartData.categories.push(item[0])
								data.push(item[1][0])
								break;
							default:
								break;
						}

					})
					if (this.current === 0) {
						this.chartData.series = [{
								name: "组合有功总电能",
								pointShape: "none",
								data: data1
							},
							{
								name: "正向有功总电能",
								pointShape: "none",
								data: data2
							},
							{
								name: "反相有功总电能",
								pointShape: "none",
								data: data3
							},
						]
					} else {
						this.chartData.series = [{
							name: "总电能",
							data
						}]
					}

					return
				}
			},
			//年月日数据整理
			filterDate() {
				let startTime, endTime;
				if (this.current === 1) {
					startTime = `${this.year}-${this.month}-01 00:00:00`
					endTime = `${this.year}-${this.month}-31 00:00:00`
				} else if (this.current === 2) {
					startTime = `${this.year}-01-01 00:00:00`
					endTime = `${this.year}-12-31 00:00:00`
				} else {
					startTime = `${this.year}-${this.month}-${this.day} 00:00:00`,
						endTime = `${this.year}-${this.month}-${this.day} 00:00:00`
				}
				return {
					startTime,
					endTime
				}
			},
		},
		mounted() {
			this.getChartsData(this.type)
		}
	}
</script>

<style scoped lang='scss'>
	.card_chart {
		.date_mouth {
			position: absolute;
			width: 100%;
			top: 100rpx;
			left: 0;
			height: 80rpx;
			background-color: #f2f2f2;
			display: flex;
			justify-content: space-around;
			align-items: center;

			.date_mouth_center {
				text {
					padding: 0 8rpx;
				}

				.iconfont {
					color: skyblue;
				}
			}
		}

		.content {
			padding-top: 100rpx;

			.charts-box {
				.title {
					text-align: center;

					.word {
						font-size: 24rpx
					}

					.count {
						font-size: 30rpx;
						font-weight: bold;
					}
				}

				.charts {
					height: 500rpx;
				}
			}
		}
	}

	.picker-view {
		width: 750rpx;
		height: 600rpx;
		margin-top: 20rpx;
	}

	.item {
		line-height: 100rpx;
		text-align: center;
	}
</style>